package com.huaweicloud.metastudio.voicedrive;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.core.region.Region;
import com.huaweicloud.sdk.metastudio.v1.MetaStudioClient;
import com.huaweicloud.sdk.metastudio.v1.model.CreateTTSAReq;
import com.huaweicloud.sdk.metastudio.v1.model.CreateTtsaRequest;
import com.huaweicloud.sdk.metastudio.v1.model.CreateTtsaResponse;
import com.huaweicloud.sdk.metastudio.v1.model.DigitalAssetInfo;
import com.huaweicloud.sdk.metastudio.v1.model.ListAssetsRequest;
import com.huaweicloud.sdk.metastudio.v1.model.ListAssetsResponse;
import com.huaweicloud.sdk.metastudio.v1.model.ListTtsaDataRequest;
import com.huaweicloud.sdk.metastudio.v1.model.ListTtsaDataResponse;
import com.huaweicloud.sdk.metastudio.v1.model.ListTtsaJobsRequest;
import com.huaweicloud.sdk.metastudio.v1.model.ListTtsaJobsResponse;
import com.huaweicloud.sdk.metastudio.v1.region.MetaStudioRegion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MetaStudioVoiceDrive {
    private static final Logger logger = LoggerFactory.getLogger(MetaStudioVoiceDrive.class);

    public static void main(String[] args) throws InterruptedException {
        System.out.println("Start HUAWEI CLOUD MetaStudio Voice Drive Java Demo...");

        ICredential auth = getCredential("YOUR AK", "YOUR SK","YOUR PROJECT ID");

        // 初始数字人服务的客户端
        MetaStudioClient client = getClient(MetaStudioRegion.CN_NORTH_4, auth);

        // 获取语音驱动任务列表
        ListTTSAJobs(client);

        // 创建语音驱动任务
        String jobId = createTTSAJob(client);

        // 创建任务后需要等待 3秒后 再查询
        Thread.sleep(3000);
        // 获取语音驱动任务详情
        ListTTSAData(client, jobId);
    }

    /**
     * 查询语音驱动任务列表
     *
     * @param client MetaStudio client
     * @return 查询语音驱动任务列表响应
     */
    public static ListTtsaJobsResponse ListTTSAJobs(MetaStudioClient client) {
        System.out.println("ListTTSAJobs start");
        try {
            ListTtsaJobsRequest request = new ListTtsaJobsRequest();
            ListTtsaJobsResponse response = client.listTtsaJobs(request);
            System.out.println("ListTtsaJobsResponse :" + response.toString());
            return response;
        } catch (ConnectionException | RequestTimeoutException e) {
            System.out.println("there is some error, exception:" + e);
        }
        return null;
    }

    /**
     * 创建语音驱动任务
     *
     * @param client MetaStudio client
     * @return 语音驱动任务ID
     */
    public static String createTTSAJob(MetaStudioClient client) {
        System.out.println("createTTSAJob start");
        // 动作资产查询条件
        ListAssetsRequest listMotionAssetsRequest = new ListAssetsRequest()
                .withAssetSource(ListAssetsRequest.AssetSourceEnum.ALL)
                .withAssetType(DigitalAssetInfo.AssetTypeEnum.ANIMATION.getValue())
                .withName("小芸_右手打招呼");

        // 音色资产查询条件
        ListAssetsRequest listVoiceAssetsRequest = new ListAssetsRequest()
                .withAssetSource(ListAssetsRequest.AssetSourceEnum.ALL)
                .withAssetType(DigitalAssetInfo.AssetTypeEnum.VOICE_MODEL.getValue())
                .withName("亲切女声");

        try {
            // 查询音色资产
            ListAssetsResponse voiceAssetsResponse = client.listAssets(listVoiceAssetsRequest);
            String voiceAssetId = voiceAssetsResponse.getAssets().get(0).getAssetId();
            System.out.println(voiceAssetId);
            // 查询动作资产
            ListAssetsResponse motionAssetsResponse = client.listAssets(listMotionAssetsRequest);
            String motionAssetId = motionAssetsResponse.getAssets().get(0).getAssetId();
            System.out.println(motionAssetId);
            // 含动作标签的语音文本
            String text = String.format("<speak>大家好，我是云笙<insert-action id=\"%s\"/>，这个是MetaStudio语音驱动的测试用例。</speak>" , motionAssetId);

            CreateTTSAReq createTtsaReq = new CreateTTSAReq()
                    .withVoiceAssetId(voiceAssetId)   // 音色ID
                    .withEmotion("HAPPY")   // 情感标签
                    .withPitch(100)   // 音高
                    .withSpeed(100)   // 语速
                    .withVolume(140)  // 音量
                    .withText(text);   // 带动作标签的文本

            CreateTtsaRequest request = new CreateTtsaRequest()
                    .withBody(createTtsaReq);
            CreateTtsaResponse response = client.createTtsa(request);
            System.out.println("createTTSAJob :" + response.toString());
            logger.info(response.toString());
            return response.getJobId();
        } catch (ConnectionException | RequestTimeoutException e) {
            System.out.println("there is some error, exception:" + e);
        }
        return null;
    }

    /**
     * 获取语音驱动数据
     *
     * @param client MetaStudio client
     * @param jobId 语音驱动任务ID
     * @return 查询语音驱动任务详情响应
     */
    public static ListTtsaDataResponse ListTTSAData(MetaStudioClient client, String jobId) {
        System.out.println("ListTTSAData start");
        try {
            ListTtsaDataRequest request = new ListTtsaDataRequest()
                    .withJobId(jobId);
            ListTtsaDataResponse response = client.listTtsaData(request);
            logger.info(response.toString());
            System.out.println("ListTTSAData :" + response);
            return response;
        } catch (ConnectionException | RequestTimeoutException e) {
            System.out.println("there is some error, exception:" + e);
        }
        return null;
    }

    /**
     * 创建鉴权凭证
     *
     * @param ak 租户帐号对应的 Access Key（AK）
     * @param sk 租户帐号对应的 Secret Access Key（SK）
     * @return 鉴权凭证
     */
    public static ICredential getCredential(String ak, String sk, String projectId) {
        return new BasicCredentials()
                .withAk(ak)
                .withSk(sk)
                .withProjectId(projectId);
    }

    /**
     * 创建MetaStudio client
     *
     * @param region region信息
     * @param auth 鉴权凭证
     * @return MetaStudio client
     */
    public static MetaStudioClient getClient(Region region, ICredential auth) {
        // 使用默认配置
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        config.withIgnoreSSLVerification(true);

        // 初始化metaStudio服务的客户端
        return MetaStudioClient.newBuilder()
                .withHttpConfig(config)
                .withCredential(auth)
                .withRegion(region) // 选择服务所在区域
                .build();
    }
}
